import 'package:flutter/material.dart';

class AppLifeCycleDemo extends StatefulWidget {
  AppLifeCycleDemo({Key key}) : super(key: key);

  @override
  _AppLifeCycleDemoState createState() => _AppLifeCycleDemoState();
}

class _AppLifeCycleDemoState extends State<AppLifeCycleDemo>
    with WidgetsBindingObserver {
  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  ///生命周期变化时回调
//  resumed:应用可见并可响应用户操作,app进入前台
//  inactive:用户可见，但不可响应用户操作，比如来了个电话,前后台切换的过渡状态
//  paused:已经暂停了，用户不可见、不可操作，app进入后台
//  suspending：应用被挂起，此状态IOS永远不会回调

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print('didChangeAppLifecycleState');
    print('state = $state');
    if (state == AppLifecycleState.paused) {
      print("app 进入后台");
    } else if (state == AppLifecycleState.resumed) {
      print("app 进入前台");
    } else if (state == AppLifecycleState.inactive) {
      // 不常用，应用程序处于非活动状态，并且未收到用户输入时调用，比如来个电话时
    } else if (state == AppLifecycleState.detached) {
      print("app detached");
    }
  }

  // 本地化语言改变回调
  @override
  void didChangeLocales(List<Locale> locale) {
    print('didChangeLocales,$locale');
    super.didChangeLocales(locale);
  }

  // 内存不足警告回调
  @override
  void didHaveMemoryPressure() {
    super.didHaveMemoryPressure();
  }

  // didChangePlatformBrightness // 系统亮度改变回调
  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('flutter app 生命周期'),
      ),
      body: ListView(
        children: [
          Container(
            child: Text('app生命周期'),
          )
        ],
      ),
    );
  }
}
